package org.sjlt.marc.dataservices;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.Date;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Iterator;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.hibernate.util.StringHelper;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.sjlt.marc.common.BigHelpDBConnection;
import org.sjlt.marc.common.Queries;
import org.sjlt.marc.resources.userData;
import org.sjlt.marc.workers.CreateUser;
import org.sjlt.marc.workers.FindUser;

public class UserInfoService extends HttpServlet 
{
	private static final long serialVersionUID = -5201246004913810348L;

	public UserInfoService() {
        super();
    }

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doPost(request, response);
	}

	@SuppressWarnings({ "unchecked", "unused" })
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException 
	{
		JSONObject output = new JSONObject();
		response.setContentType("application/json");
		PrintWriter pw = response.getWriter();
		String requestType = request.getParameter("RequestType");
		BigHelpDBConnection bhdbcon = new BigHelpDBConnection("sjlt_marc");
		
		if(StringHelper.isNotEmpty(request.getParameter("method")))
		{
			String method = request.getParameter("method");
			
			if("CheckForUser".equals(method))
			{
				String userid = request.getParameter("UserId");
				FindUser uFind = new FindUser(userid);
				
				userData currUser = uFind.getUserInfo();
				
				output.put("User",currUser);
			}
			else if("AuthenticateUser".equals(method))
			{
				try
				{
					String userid = request.getParameter("userid");
					String enteredPW = request.getParameter("enteredPass");
					String correctPW = null;
					String AccessLevel = null;
					
					Connection conn = bhdbcon.getConnection();
					PreparedStatement ps = conn.prepareStatement(Queries.SQL_AUTHENTICATE_USER);
					try
					{
						ps.setString(1, userid);
						ResultSet rs = ps.executeQuery();
						while(rs.next())
						{
							correctPW = rs.getString("Password");
							AccessLevel = rs.getString("Access_Level");
						}
					}
					finally
					{
						ps.close();
						conn.close();
					}
	
					if(enteredPW.equals(correctPW)) //Doesn't actually check for username, just pw above
					{
						output.put("userid", userid);
						output.put("validLogin", true);
						output.put("Access_Level",AccessLevel);
					}
					else
					{
						output.put("userid", userid);
						output.put("validLogin", false);
					}
				}
				catch(SQLException se)
				{
					se.printStackTrace();
				}
				finally
				{
				}
			}
			else if("CreateUser".equals(method))
			{
				String UserId = request.getParameter("UserId");
				String FName = request.getParameter("FName");
				String MInitial = request.getParameter("MInitial");
				String LName = request.getParameter("LName");
				String Pref_Name = request.getParameter("Pref_Name");
				Date DOB = Date.valueOf(request.getParameter("DOB"));
				String Gender = request.getParameter("Gender");
				String Address = request.getParameter("Address");
				String City = request.getParameter("City");
				String Zip = request.getParameter("Zip");
				String Phone = request.getParameter("Phone");
				String Email = request.getParameter("Email");
				String Shirt = request.getParameter("Shirt");
				String School = request.getParameter("School");
				Integer Grade = Integer.parseInt(request.getParameter("Grade"));
				String Highest_Sacrament = request.getParameter("Highest_Sacrament");
				Integer Confirmation = Integer.parseInt(request.getParameter("Confirmation"));
				String Access_Level = request.getParameter("Access_Level");
				String InsuranceCo = request.getParameter("InsuranceCo");
				String InsuranceNum = request.getParameter("InsuranceNum");
				String Medications = request.getParameter("Medications");
				String Allergies = request.getParameter("Allergies");
				String MedicalIssues = request.getParameter("MedicalIssues");
				Integer PermissionToTreat = Integer.parseInt(request.getParameter("PermissionToTreat"));
				String EmgContact = request.getParameter("EmgContact");
				String EmgRelation = request.getParameter("EmgRelation");
				String EmgNumber = request.getParameter("EmgNumber");
				String ReportsTo = request.getParameter("ReportsTo");
				String Picture  = request.getParameter("Picture");

				CreateUser UC = new CreateUser(UserId, FName, MInitial, LName, Pref_Name, DOB, Gender, Address, City, Zip, Phone, Email, Shirt, School,  Grade,
						Highest_Sacrament,  Confirmation, Access_Level, InsuranceCo, InsuranceNum, Medications, Allergies, MedicalIssues, PermissionToTreat,
						EmgContact, EmgRelation, EmgNumber, ReportsTo, Picture);
				
				UC.run();
				output.put("Successful", 1);
			}
			else if("GatherUserList".equals(method))
			{
				FindUser uFind = new FindUser();
				
				JSONArray users = new JSONArray();
				
				Iterator<userData> userIterator = uFind.getUserList().iterator();
				while(userIterator.hasNext())
				{
					users.add(userIterator.next());
				}
				
				output.put("UserList",users);
			}
			else if("AssociateNewAlias".equals(method))
			{
				try 
				{
					String UserID = request.getParameter("UserID");
					String Alias = request.getParameter("Alias");
					String AliasType = request.getParameter("AliasType");
					
					Connection conn = bhdbcon.getConnection();
					PreparedStatement ps = conn.prepareStatement(Queries.SQL_ASSOCIATE_NEW_ALIAS);
					
					ps.setString(1,UserID);
					ps.setString(2,Alias);
					ps.setString(3,AliasType);
					ps.setBoolean(4, true);
					
					Integer returnVal = ps.executeUpdate();
					
					output.put("Result", returnVal);
				} 
				catch (SQLException e) 
				{
					e.printStackTrace();
				}
				finally
				{
					bhdbcon.closeConnection();
				}
			}
			else if("GatherCarrierList".equals(method))
			{
				try
				{
					Connection conn = bhdbcon.getConnection();
					PreparedStatement ps = conn.prepareStatement(Queries.SQL_GATHER_ACTIVE_CARRIERS);
					
					JSONArray carriers = new JSONArray();
					JSONArray carrierIDs = new JSONArray();
					ResultSet rs = ps.executeQuery();
					
					while(rs.next())
					{
						carriers.add(rs.getString("friendly_name"));
						carrierIDs.add(rs.getString("carrier_id"));
					}
					
					output.put("Carriers", carriers);
					output.put("CarrierIDs", carrierIDs);
				}
				catch(Exception e)
				{
					e.printStackTrace();
				}
			}
			else if("GatherKnownAliases".equals(method))
			{
				try
				{
					Connection conn = bhdbcon.getConnection();
					PreparedStatement ps = conn.prepareStatement(Queries.SQL_GATHER_KNOWN_ALIASES);
					
					String UserId = request.getParameter("UserId");
					
					ps.setString(1, UserId);
					
					JSONArray rows = new JSONArray();
					JSONArray types = new JSONArray();
					JSONArray IDs = new JSONArray();
					JSONArray Active = new JSONArray();
					ResultSet rs = ps.executeQuery();
					
					while(rs.next())
					{
						rows.add(rs.getString("RowID"));
						types.add(rs.getString("AliasType"));
						IDs.add(rs.getString("Alias"));
						Active.add(rs.getInt("Active"));
					}
					
					output.put("Rows", rows);
					output.put("Types", types);
					output.put("Aliases", IDs);
					output.put("Active", Active);
				}
				catch(Exception e)
				{
					e.printStackTrace();
				}
			}
			
			response.setContentType("application/json");
			response.getWriter().println(output.toJSONString());
		}
	}

}